package org.linlinjava.litemall.wx.task;

import com.google.common.collect.Maps;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.db.domain.LitemallActivityGroupon;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.ActivityGrouponService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TaskStartupRunner implements ApplicationRunner {

    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ActivityGrouponService grouponService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<LitemallOrder> orderList = orderService.queryUnpaid(SystemConfig.getOrderUnpaid());

        List<Integer> orderIds = orderList.stream().map(LitemallOrder::getId).collect(Collectors.toList());
        Map<String, Object> map = Maps.newConcurrentMap();
        map.put("orderIds", orderIds);
        List<LitemallActivityGroupon> groupons = grouponService.findByParams(Collections.singletonList(map));
        List<Integer> grouponOrderIds = groupons.stream().map(LitemallActivityGroupon::getOrderId).collect(Collectors.toList());
        for (LitemallOrder order : orderList) {
            LocalDateTime add = order.getAddTime();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expire = add.plusMinutes(SystemConfig.getOrderUnpaid());
            if (expire.isBefore(now)) {
                // 已经过期，则加入延迟队列
                if (grouponOrderIds.contains(order.getId())) {
                    taskService.addTask(new ActivityOrderUnpaidTask(order.getId(), 0));
                } else {
                    taskService.addTask(new OrderUnpaidTask(order.getId(), 0));
                }
            } else {
                // 还没过期，则加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, expire);
                if (grouponOrderIds.contains(order.getId())) {
                    taskService.addTask(new ActivityOrderUnpaidTask(order.getId(), delay));
                } else {
                    taskService.addTask(new OrderUnpaidTask(order.getId(), delay));
                }
            }
        }
    }
}